//
//  CoreDataManager.m
//  Coredata
//
//  Created by 王斌 on 16/3/8.
//  Copyright © 2016年 王斌. All rights reserved.
//

#import "CoreDataManager.h"
@implementation CoreDataManager

+ (instancetype)shareInstance
{
    static CoreDataManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CoreDataManager alloc] init];
    });
    return  manager;
}


#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

/// 返回沙盒路径
- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.Coredata" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"WB_Shine" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
}
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"HealthKit.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    
#pragma mark 版本升级后必然崩溃的解决方法
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:@(YES), NSMigratePersistentStoresAutomaticallyOption, @(YES), NSInferMappingModelAutomaticallyOption,  nil];
    
    
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    
    // 懒加载
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


/// 查找
- (NSArray *)selectAll:(NSNumber *)year month:(NSNumber *)month day:(NSNumber *)day hour:(NSNumber *)hour{
    
    [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"HealthKit" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    if (hour) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"year = %@ AND month = %@ AND day = %@ AND hour = %@", year, month, day, hour];
        [fetchRequest setPredicate:predicate];
    }else{
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"year = %@ AND month = %@ AND day = %@", year, month, day];
        [fetchRequest setPredicate:predicate];
    }
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"day"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {

    }
    return fetchedObjects;
}

/// 查找
- (NSArray *)selectSevenDay{
    //日期在七天之内:
    NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone systemTimeZone] secondsFromGMTForDate:[NSDate date]]];
    NSTimeInterval timeInterval= [endDate timeIntervalSinceReferenceDate];
    timeInterval -=3600*24*7;
    NSDate *beginDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"HealthKit" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    
    ///NSDate转化成NSString
    NSString *beginStr = [NSString stringWithFormat:@"%@",beginDate];
    
    /// 截取年 月 日 小时
    NSString *beginTempYear = [beginStr substringToIndex:4];
    NSString *beginTempMonth = [beginStr substringWithRange:(NSMakeRange(5, 2))];
    NSString *beginTempDay = [beginStr substringWithRange:(NSMakeRange(8, 2))];
    NSNumber *beginYear = [NSNumber numberWithInt:[beginTempYear intValue]];
    NSNumber *beginMonth = [NSNumber numberWithInt:[beginTempMonth intValue]];
    NSNumber *beginDay = [NSNumber numberWithInt:[beginTempDay intValue]];
    
    ///NSDate转化成NSString
    NSString *endStr = [NSString stringWithFormat:@"%@",endDate];
    
    /// 截取年 月 日 小时
    NSString *endTempYear = [endStr substringToIndex:4];
    NSString *endTempMonth = [endStr substringWithRange:(NSMakeRange(5, 2))];
    NSString *endTempDay = [endStr substringWithRange:(NSMakeRange(8, 2))];
    NSNumber *endYear = [NSNumber numberWithInt:[endTempYear intValue]];
    NSNumber *endMonth = [NSNumber numberWithInt:[endTempMonth intValue]];
    NSNumber *endDay = [NSNumber numberWithInt:[endTempDay intValue]];

    if ([beginYear integerValue] == [endYear integerValue] && [beginMonth integerValue] == [endMonth integerValue]) {
        NSPredicate *predicate =[NSPredicate predicateWithFormat:@"day >= %@ AND day <= %@", beginDay,endDay];
        
        [fetchRequest setPredicate:predicate];
    }else if ([beginYear integerValue] == [endYear integerValue]){
        NSPredicate *predicate =[NSPredicate predicateWithFormat:(@"( month = %@ && day >= %@ ) && ( month = %@ && day <= %@ )" ), beginMonth, beginDay, endMonth, endDay];
        
        [fetchRequest setPredicate:predicate];
    }

    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"day"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"查询错误");
    }
    return fetchedObjects;

}

- (void)insertData:(NSString *)date count:(NSInteger)count{
    HealthKit *health = [NSEntityDescription insertNewObjectForEntityForName:@"HealthKit" inManagedObjectContext:self.managedObjectContext];
    NSString *tempYear = [date substringToIndex:4];
    NSString *tempMonth = [date substringWithRange:(NSMakeRange(5, 2))];
    NSString *tempDay = [date substringWithRange:(NSMakeRange(8, 2))];
    NSString *tempHour = [date substringWithRange:(NSMakeRange(11, 2))];
    NSNumber *year = [NSNumber numberWithInt:[tempYear intValue]];
    NSNumber *month = [NSNumber numberWithInt:[tempMonth intValue]];
    NSNumber *day = [NSNumber numberWithInt:[tempDay intValue]];
    NSNumber *hour = [NSNumber numberWithInt:[tempHour intValue]];
    NSInteger daytemp = [day intValue];
    NSInteger hourtemp = [hour intValue];
    if ([hour intValue] + 8 > 23) {
        daytemp += 1;
        day = [NSNumber numberWithInteger:daytemp];
        
        hourtemp -= 16;
        hour = [NSNumber numberWithInteger:hourtemp];
    }else{
        hourtemp += 8;
        hour = [NSNumber numberWithInteger:hourtemp];
    }
    
    
    NSArray *arr = [self selectAll:year month:month day:day hour:hour];
    if (arr.count != 0) {
        for (HealthKit *temp in arr) {
            [self.managedObjectContext deleteObject:temp];
        }
        [self saveContext];
    }
    health.year = year;
    health.month = month;
    health.day = day;
    health.hour = hour;
    health.count = [NSNumber numberWithInteger:count];
    [self saveContext];
    
    
}


@end
